package com.asm.handler;

import com.asm.message.RpcRequestMessage;
import com.asm.message.RpcResponseMessage;
import com.asm.rpc.service.HelloService;
import com.asm.rpc.service.ServicesFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage message) throws Exception {
            //如果返回结果没问题
            RpcResponseMessage response = new RpcResponseMessage();

            //解决序列号不一致的问题
            response.setSequenceId(message.getSequenceId());

        Object invoke = null;
        try {
            //根据接口的名字找到接口对应实现类的对象
            HelloService service = (HelloService) ServicesFactory.
             getService(Class.forName(message.getInterfaceName()));
            //根据对象找到真正要调用的方法
            Method method = service.getClass().getMethod(message.getMethodName(), message.getParameterTypes());
            invoke = method.invoke(service, message.getParameterValue());
            //System.out.println(invoke);
            //把成功或异常的信息封装到一个响应消息里
            response.setReturnValue(invoke);

        } catch (Exception e) {
           e.printStackTrace();
            String s = e.getCause().getMessage();
            //输出异常消息
           response.setExceptionValue(new Exception("远程调用出错:"+s));
        }
        ctx.writeAndFlush(response);
        //因为是服务端调用的，写入消息是从服务端从下往上出站，到客户端，客户端读取消息

    }

   /* public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        RpcRequestMessage message = new RpcRequestMessage(
                1,
                "com.asm.rpc.service.HelloService",
                "sayHello",
                String.class,
                new Class[]{String.class},
                new Object[]{"张三"}
        );

    }*/
}
